package org.example.rabbitmq.routing;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author taritari
 * @date 2023-11-22 15:01
 * @description
 */
public class Consumer {
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("****");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
            connectionFactory.setVirtualHost("my_vhost");
            Connection connection = null;
            Channel channel = null;
            final String queueName = Thread.currentThread().getName();
            try {
                connection = connectionFactory.newConnection("生产者");
                channel = connection.createChannel();
                channel.basicConsume(queueName, true, new DeliverCallback() {
                    @Override
                    public void handle(String s, Delivery delivery) throws IOException {
                        System.out.println(delivery.getEnvelope().getDeliveryTag());
                        System.out.println(queueName+"收到消息是:"+new String(delivery.getBody(),"UTF-8"));
                    }
                }, new CancelCallback() {
                    @Override
                    public void handle(String s) throws IOException {
                    }
                });


                System.out.println(queueName+"开始接收消息");
                System.in.read();
            }catch (Exception e){
                System.out.println("接收失败了");
                e.printStackTrace();
            }finally {
                if (channel != null && channel.isOpen()){
                    try {
                        connection.close();
                    }catch (Exception exception){
                        exception.printStackTrace();
                    }
                }

                if (connection != null && connection.isOpen()){
                    try {
                        connection.close();
                    }catch (Exception exception){
                        exception.printStackTrace();
                    }
                }
            }
        }
    };


    public static void main(String[] args) {
        new Thread(runnable,"queue1").start();
        new Thread(runnable,"queue3").start();
        new Thread(runnable,"queue2").start();

    }
}
